package cn.com.utt.unms.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import cn.com.utt.common.http.Client;
import cn.com.utt.common.zk.APIDiscovery;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.service.ClientService;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.utils.GraphUtils;
import cn.com.utt.unms.vo.GraphQueryParam;
import cn.com.utt.unms.vo.GraphQueryResponse;

@Service("clientService")
public class ClientServiceImpl implements ClientService {

	@Autowired
	private DeviceService deviceService;
	
	@Autowired
	private APIDiscovery apiDiscovery;
	

	@Override
	public List<GraphQueryResponse> queryHistoryByNetwork(Long networkId, Long start, Long end) {
		List<GraphQueryResponse> sums = null;
		// 根据networkId查询所有下级设备
		List<Device> devices = deviceService.queryDevicesByNetworkIds(new ArrayList<Long>(){{add(networkId);}});
		if (devices == null || devices.isEmpty()) {
			return sums;
		}
		String[] hostNames = new String[devices.size()];
		for (int i = 0; i < devices.size(); i++) {
			hostNames[i] = devices.get(i).getSn();
		}
		// 组装falcon-plus的查询参数
		GraphQueryParam params = new GraphQueryParam();
		params.setConsolFun("AVERAGE");
		params.setStartTime(start);
		params.setEndTime(end);
		params.setCounters(new String[] { "net.clients.client24g","net.clients.client5g" });
		params.setStep(60);
		params.setHostNames(hostNames);
		// 调用falcon-plus的api接口查询历史数据
		Client client = new Client();
		// 查询2.4G数据,查询5G数据
		String result = client.doPostWithJson("http://"+apiDiscovery.discover()+ "/api/v1/graph/history", JSON.toJSONString(params));
		if (result != null && result.length() > 0) {
			// 合并数据，按counter合并
			List<GraphQueryResponse> resps = JSON.parseArray(result, GraphQueryResponse.class);
			if(resps!=null){
				for (GraphQueryResponse graphQueryResponse : resps) {
					//根据绑定时间筛选出设备数据,在绑定时间之前的数据都设置为0
					for (int k = 0; k < devices.size(); k++) {
						if(graphQueryResponse.getEndpoint().equals(devices.get(k).getSn())){
							for (int k2 = 0; k2 < graphQueryResponse.getValues().size(); k2++) {
								if(devices.get(k).getBindTime().getTime()>graphQueryResponse.getValues().get(k2).getTimestamp()*1000){
									graphQueryResponse.getValues().get(k2).setValue(0.0);
								}
								
							}
						}
					}
				}
			}
			sums = GraphUtils.MergeGraphDataByCounter(resps,false);
			//计算2.4g与5g的总数据
			sums.add(GraphUtils.countGraphDataByTimestamp(sums));
		}
		return sums;
	}
}
